require 'common'
require 'drb'
require 'action'
require 'vim'

module Evil
  SERVER_PORT = 7878
  CLIENT_PORT = 7877
  @@editor = VIM::Editor.new

  def self.init
    DRb.start_service(localhost(CLIENT_PORT), @@editor)
    cid = fork do 
      require 'server'
      Server.new.start(SERVER_PORT, CLIENT_PORT)
    end
    VIM.command %{ sil autocmd! VimLeavePre * sil !kill -9 #{cid} }
  end

  def self.run(action)
    action_class = Action.constantize(action)
    if action_class.ancestors.include? RemoteAction
      DRbObject.new(nil, localhost(SERVER_PORT)).do_action(action)
    else
      action_class.new(@@editor).execute
    end
  end

  private
  def self.localhost(port)
    "druby://localhost:#{port}"
  end
end

